package com.zhao.dota.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhao.dota.contant.CacheConstant;
import com.zhao.dota.mapper.AbilityMapper;
import com.zhao.dota.model.Ability;
import com.zhao.dota.service.AbilityService;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

@Service
@CacheConfig(cacheNames = CacheConstant.ABILITY)
public class AbilityServiceImpl extends ServiceImpl<AbilityMapper, Ability> implements AbilityService {


    @Override
    public int updateList(List<Ability> itemList) {
        for (Ability ability : itemList) {
            Ability old = getByName(ability.getName());
            if (old != null) {
                ability.setId(old.getId());
            }
        }
        return saveOrUpdateBatch(itemList) ? itemList.size() : 0;
    }


    @Override
    @Cacheable(key = "'name:'.concat(#name)", unless = "#result == null")
    public Ability getByName(String name) {
        LambdaQueryWrapper<Ability> query = Wrappers.lambdaQuery(Ability.class).eq(Ability::getName, name);
        return super.getOne(query);
    }

    @Override
    public List<Ability> getByHeroName(String heroName) {
        LambdaQueryWrapper<Ability> query = Wrappers.lambdaQuery(Ability.class).eq(Ability::getHeroName, heroName);
        return super.list(query);
    }

    @Override
    @Cacheable(key = "'id:'.concat(#id)", unless = "#result == null")
    public Ability getById(Serializable id) {
        return super.getById(id);
    }

    @Override
    @Caching(evict = {@CacheEvict(key = "'id:'.concat(#entity.id)"), @CacheEvict(key = "'name:'.concat(#entity.name)")})
    public boolean save(Ability entity) {
        return super.save(entity);
    }

    @Override
    @Caching(evict = {@CacheEvict(key = "'id:'.concat(#entity.id)"), @CacheEvict(key = "'name:'.concat(#entity.name)")})
    public boolean updateById(Ability entity) {
        return super.updateById(entity);
    }
}
